import logging
import json
import xml.etree.ElementTree as ET
from fastapi import Request

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("wx_message_parser")

class WxMessageParser:
    """微信消息解析工具类"""
    
    @staticmethod
    async def parse_message(request: Request) -> dict:
        """
        解析微信推送的消息
        
        参数:
        - request: FastAPI请求对象
        
        返回:
        - 解析后的消息字典
        """
        try:
            # 读取请求体内容
            body = await request.body()
            body_content = body.decode('utf-8')
            logger.info(f"收到消息内容: {body_content}")
            
            # 尝试判断消息格式是XML还是JSON
            if body_content.strip().startswith('{') and body_content.strip().endswith('}'):
                # JSON格式
                try:
                    message = json.loads(body_content)
                    logger.info(f"成功解析JSON消息: {message}")
                    return message
                except json.JSONDecodeError as e:
                    logger.error(f"JSON解析失败: {str(e)}")
                    return {"Error": f"JSON解析失败: {str(e)}"}
            else:
                # 尝试解析为XML
                try:
                    root = ET.fromstring(body_content)
                    message = {}
                    
                    # 将XML转换为字典
                    for child in root:
                        message[child.tag] = child.text
                    
                    logger.info(f"成功解析XML消息: {message}")
                    return message
                except ET.ParseError as e:
                    logger.error(f"XML解析失败: {str(e)}")
                    return {"Error": f"XML解析失败: {str(e)}"}
        
        except Exception as e:
            logger.error(f"消息解析异常: {str(e)}", exc_info=True)
            return {"Error": f"消息解析异常: {str(e)}"}
    
    @staticmethod
    def create_text_response(content: str) -> dict:
        """
        创建文本回复
        
        参数:
        - content: 回复内容
        
        返回:
        - 回复消息字典
        """
        return {"Content": content}
    
    @staticmethod
    def create_success_response() -> str:
        """创建成功响应"""
        return "success" 